const app = getApp();
const wxApi = app.globalData.wxApi;
const Api = app.globalData.Api;
const util = app.globalData.util;
let getUserInfo = app.globalData.getUserInfo;
Page({
  data: {
    integrations: [],
    loadMoreType: 0,
    totalIntegration: ""
  },
  onLoad() {
    this.curPage = 1;
    this.init();
  },
  init() {
    let self = this;
    wxApi.setNavTitle('我的积分');
    let userInfo = getUserInfo();
    console.log( userInfo );
    this.setData({
      totalIntegration: userInfo.points
    })
    this.refresh();
  },
  onPullDownRefresh() {
    console.log( '下拉刷新' );
    this.refresh();
  },
  onReachBottom() {
    console.log( '加载更多' );
    this.loadMore();
  },
  refresh() {
    let self = this;
    this.curPage = 1;
    this.loadIntegrations(this.curPage, integrations => {
      console.log( integrations );
      wxApi.stopRefresh();
      self.setData({
        integrations: integrations
      })
    });
  },
  loadMore() {
    let self = this;
    let integrations = this.data.integrations;
    this.curPage ++;
    console.log( this.curPage );
    this.setData({
      loadMoreType: 1 // 显示加载更多
    })
    this.loadIntegrations(this.curPage, data => {
      if ( data.length ) {
        integrations = integrations.concat( data );
        self.setData({
          loadMoreType: 1, // 显示加载更多
          integrations: integrations
        })
      } else {
        self.curPage --; //没有更多则页码减一
        self.setData({
          loadMoreType: 2 // 显示无更多
        })
      }
    })
  },
  loadIntegrations( pageNo, callback ) {
    let pageSize = 20;
    pageNo = pageNo || 1;
    let params = {
      pageNo,
      pageSize
    }
    Api.getUserIntegrations(params, data => {
      let integrations = data.records;
      integrations = integrationsDateFomat( integrations );
      callback( integrations );
    })
  }
})
function integrationsDateFomat(integrations) {
  let newIntergrations = [];
  for ( let i = 0, len = integrations.length; i < len; i ++ ) {
    let integ = integrations[ i ];
    integ.dateTime = util.dateFormat( 'yyyy年MM月dd日', integ.createTime );
    newIntergrations.push( integ );
  }
  return newIntergrations;
}
